package mhuu.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

import mhuu.constant.AppConfig;
import mhuu.util.TextUtil;
import mhuu.view.HttpRequestPanel;

public class HttpProtocolTxtService {
	
	public static int getContentLength(String txt) throws Exception { 
		int index=txt.indexOf("\n\n");
		String body=txt.substring(index+2, txt.length()); 
		
		return body.getBytes("utf-8").length;
	}
	 
	public static String getOkRequestContent(String txt,String address,String host) throws Exception { 
		int index=txt.indexOf("\n\n");
		String requst=txt.substring(0,index);  
		address=address.replaceAll("http://", "");
		address=address.replaceAll("https://", ""); 
		if (address.contains("/")) {
			int addressIndex=address.indexOf("/"); 
			String path=address.substring(addressIndex,address.length());  
			System.out.println(path);
			String[] strArray=requst.split(" ");
			System.out.println(strArray[1]);
			requst=requst.replace(" "+strArray[1]+" "," "+ path+" ");
		}
		String body=txt.substring(index+2, txt.length()); 
		boolean isGzip= HttpRequestPanel.jCheckBox.isSelected();
		if (isGzip) {
			body=TextUtil.encodeParams(body).replaceAll("\n", "");
		}
		int contentLength=body.getBytes("utf-8").length; 
		  if (requst.contains("Host")) {
				String[] strArray=requst.split("\n");
				for (int i = 0; i < strArray.length; i++) {
					if (strArray[i].contains("Host")) {
						requst=requst.replace(strArray[i],"Host: "+host);
					}
				}
				
			}else {
				
				requst+="\nHost: "+host;
		}
	   if (requst.contains("Content-Length")) {
				String[] strArray=requst.split("\n");
				for (int i = 0; i < strArray.length; i++) {
					if (strArray[i].contains("Content-Length")) {
						requst=requst.replace(strArray[i],"Content-Length: "+body.getBytes("utf-8").length);
					}
				}
				
			}else {
				
				requst+="\nContent-Length: "+body.getBytes("utf-8").length;
		}
	   
 
		if (!requst.endsWith("\n\n")) {
			if (requst.endsWith("\n")) {
				requst=requst+"\n";
			}else {
				requst=requst+"\n\n";
			}
		}
		String content=requst+body;
		return content;
	}
	public static void main(String[] args) throws UnsupportedEncodingException {
		String txt=AppConfig.HttpRequestDefult;
		txt+="123";
		int index=txt.indexOf("\n\n");
		String requst=txt.substring(0,index); 
		
		String body=txt.substring(index+2, txt.length()); 
		requst+="\nContent-Length: "+body.getBytes("utf-8").length+"\n\n";
		
		System.out.println("["+requst+body+"]");
		 
	}
	
	
}
